package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.Freeze;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FreezeService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.Duration;

@DubboService
public class FreezeServiceImpl implements FreezeService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MongoTemplate mongoTemplate;


    //保存用户信息
    @Override
    public String saveFreeze(Freeze freeze) {
        mongoTemplate.save(freeze);
        return "操作完成";
    }



    //调用redis设置冻结状态及冻结天数
    @Override
    public void saveStatus(Freeze freeze) {
        switch (freeze.getFreezingTime()) {
            case 1:   //向redis中存储状态,定时三天
                stringRedisTemplate.opsForValue().set("freeze_" + freeze.getUserId(), freeze.getFreezingRange() + "_3", Duration.ofDays(3));
                break;
            case 2:   //向redis中存储状态,定时七天
                stringRedisTemplate.opsForValue().set("freeze_" + freeze.getUserId(), freeze.getFreezingRange() + "_7", Duration.ofDays(7));
                break;
            case 3:   //向redis中存储状态,永久冻结
                stringRedisTemplate.opsForValue().set("freeze_" + freeze.getUserId(), freeze.getFreezingRange() + "_0");
                break;
            default:
                break;
        }
    }

    // 根据用户id查询用户的状态
    @Override
    public Freeze findById(Integer userId) {
        // 创建条件
        Query query = Query.query(Criteria.where("userId").is(userId));
        // 查询
        Freeze freeze = mongoTemplate.findOne(query, Freeze.class);
        return freeze;
    }

    @Override
    public String findRedisState(Integer userId) {
        // 1. 取出redis中存储的用户状态
        String status = stringRedisTemplate.opsForValue().get("freeze_" + userId);
        // 2. 对字符串进行判断
        if (status == null) { // 说明该用户不存在冻结状态
            // 3. 取出用户状态
            Freeze freeze = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId)), Freeze.class);
            // 4. 修改冻结状态
            freeze.setUserStatus("1");
            // 5. 保存
            saveFreeze(freeze);
            // 6. 返回状态码为1
            return "1";
        }
        return "2";
    }

    //用户解冻
    @Override
    public void deleteStatus(Freeze freeze, String reasonsForThawing) {

        //1. 删除redis中数据
        stringRedisTemplate.delete("freeze"+freeze.getUserId());
        //2. 封装解禁原因
        freeze.setReasonsForThawing(reasonsForThawing);
        //3. 将状态改为1
        freeze.setUserStatus("1");
        //4. 保存
        saveFreeze(freeze);
    }
}
